<template>
	<view class="my-upload">
		<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" v-bind="$attrs"></u-upload>
	</view>
</template>
<script>
	import {
		baseUrl
	} from "@/utils/url";
	export default {
		props: {
			value: {
				type: Array,
				default: () => [],
			},
		},
		data() {
			return {
				fileList: [],
			};
		},
		watch: {
			value: {
				immediate: true,
				handler(val, old) {
					this.fileList = val;
				},
			},
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
				console.log("this.fileList", this.fileList);
				this.$emit("input", this.fileList);
				this.$emit("change", this.fileList);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				console.log("lists", lists);
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							name: result.fileName || `${Date.now()}`,
							url: result,
						})
					);
					console.log("this.fileList", this.fileList);
					this.$emit("input", this.fileList);
					this.$emit("change", this.fileList);
					fileListLen++;
				}
			},
			async uploadFilePromise(src) {
				let url = '';
				return new Promise((resolve, reject) => {
					uni.compressImage({
						src: src,
						quality: 50,
						success: res => {
							url = res.tempFilePath;
							uni.uploadFile({
								url: baseUrl + "/fileServer/upload",
								filePath: url,
								name: "file",
								formData: {
									dir: "",
								},
								success: (res) => {
									const data = JSON.parse(res.data);
									console.log("res.data", data.data);
									resolve(data.data.fileUrl);
								},
							});
						}
					})
					
				});
			},
		},
	};
</script>
<style lang="scss" scoped>
	.my-upload {
		width: 100%;
	}
</style>